<?php
/**
 * Created by PhpStorm.
 * User: JSQ-SL
 * Date: 2018/10/19
 * Time: 16:16
 */

namespace app\index\table;

use app\index\controller\Login;
use app\index\service\ExcelService;
use think\Db;

class BookAlterTable extends BaseTable
{
    protected static $table = 'ASSET_BOOK_ALTER';
    protected static $view = 'V_ASSET_BOOK_ALTER';
    protected static $pk = 'ALTER_NO';

    static public function table(){
        return Db::table(static::$view);
    }

    static public function add($data){
        $data['ALTER_NO'] = self::getNextId();
        $data['USER_ID'] = Login::getUserId();
        $data['OPER_DATE'] = date('Y-m-d');
        self::toDate($data,'ALTER_DATE');
        self::toDate($data,'OPER_DATE');
        return Db::table(static::$table)->insert($data);
    }

    static public function delete($where){
        return Db::table(static::$table)->where($where)->delete();
    }

    public static function getNextId(){
        $year = date('Y');
        $numMaxRecord = Db::table(static::$table)
            ->field('max(SUBSTR(ALTER_NO,5,4)) as NUM')
            ->where([['SUBSTR(ALTER_NO,1,4)','=',$year]])
            ->fetchSql(true)
            ->find();
        $numMaxRecord = Db::query($numMaxRecord);
        $num = $numMaxRecord[0]['NUM'];
        if ($num == NULL) {
            $num = 0;
        }
        $num++;
        return $year.sprintf("%04d", $num);
    }

    public static function exportExcel($data,$fileName){

        $fieldList = [
            ['title'=>'预异动单编号','field'=>'PRE_ALTERINFO_NO']
            ,['title'=>'变动编号','field'=>'ALTER_NO']
            ,['title'=>'家具编号','field'=>'FURN_NO']
            ,['title'=>'家具名称','field'=>'FURN_NAME']
            ,['title'=>'状态','field'=>'STATE']
            ,['title'=>'变动类型','field'=>'ALTER_TYPE']
            ,['title'=>'变动时间','field'=>'ALTER_TIME']
            ,['title'=>'变动价格','field'=>'ALTER_PRICE']
            ,['title'=>'经手人','field'=>'CHECK_PERSON']
            ,['title'=>'负责人','field'=>'CHARGE_PERSON']
            ,['title'=>'制单人','field'=>'INPUT_NAME']
            ,['title'=>'制单时间','field'=>'INPUT_DATE']
            ,['title'=>'备注','field'=>'REMARK']
            ,['title'=>'变动前部门','field'=>'DEPART_SHORT']
            ,['title'=>'报废去向','field'=>'DISPOSE_DIRECT']
        ];

        $excel = new ExcelService();
        $excel->exportExcel($data,$fileName,$fieldList);
    }
}